#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int isBuiltInCommand(char* arg) {
	if(strcmp(arg, "exit") == 0 || strcmp(arg, "cd") == 0 || strcmp(arg, "path") == 0) 
		return 1;
	else
		return 0;
}

int main(int argc, char* argv[]) {
	char* cmd_line = malloc(sizeof(char) * 100);
	char *cmdargs[10];
	char* token = malloc(sizeof(char) * 100);
	char* dir = malloc(sizeof(char) * 100);
	char cwd[100];
	int i = 0;
	char path[100];
	strcpy (path,"myShell:usr/bin");
	char* delete;
	int pid;
	int status;
	
	while(1) {
		printf("%% ");
		scanf("%[^\n]%*c", cmd_line); //gets commands
		int argcnt = 1;		
		
		token = strtok(cmd_line, " ");  //puts the first argument into token
		cmdargs[0] = token;				//puts the argument into the string array
		while(token != NULL) {
			token = strtok(NULL, " ");
			if(token != NULL) {
				cmdargs[argcnt] = token;
				argcnt++;
			}
		}	
		
		if(isBuiltInCommand(cmdargs[0])) {
		
			if(strcmp(cmdargs[0], "exit") == 0) {
				exit(0);
			}
		
			if(strcmp(cmdargs[0], "cd") == 0) {
				for(i = 1; i < argcnt; i++) {
					strcat(dir, cmdargs[i]);
				}
				if(chdir(dir) == -1) {      //changes the directory
					printf("chdir error\n");
				}
				else {
					if (getcwd(cwd, sizeof(cwd)) != NULL) {
						fprintf(stdout, "Current working dir: %s\n", cwd);
						strcpy(dir,""); //empty the passing string
					}
					else {
						perror("getcwd() error");
					}
				}
			}
		
			if(strcmp(cmdargs[0], "path") == 0) {
				if(argcnt == 1) {
					//display path
					printf("%s\n", path);
				}
				else if(strcmp(cmdargs[1], "+") == 0) {
					strcat(path, ":");
					strcat(path, cmdargs[2]); 
					printf("%s\n", path);
				}
				else if(strcmp(cmdargs[1], "-") == 0) {
					delete = strstr(path, cmdargs[2]);
					strcpy(delete, "\0");
					printf("%s\n", path);
				}
			}
		} //end if(isBuiltInCommand) 
		
		else if(strcmp(cmdargs[1], ">") == 0 || strcmp(cmdargs[1], "<") == 0) { //need todo; i/o redirection
			//open(), close(), dup2()
		}
		
		else if(strcmp(cmdargs[1], "|") == 0) { //need todo; execve and pipes
			pid = fork();
			if(pid == 0) { //child
				
			}
			else { //parent waits
				waitpid(-1, &status, 0);
			}
		}
		   
		
	}
	
	free(cmd_line);
	free(token);
	free(dir);
	return(1);
}